import React, { useEffect } from "react";
import { Button, Checkbox, Form, Input } from "antd";
import http from "../../utils/request";
import { useDispatch } from "react-redux";
import { setListSlice } from "../../reducers/listSlice";
import { useForm } from "antd/es/form/Form";
import useDebounce from "../hooks/useDebounce";
import useCountAuth from "../hooks/useCountAuth";

function Login() {
  const { count, start, isRun } = useCountAuth(10);
  const dispatch = useDispatch();
  const onFinish = useDebounce(async (values) => {
    console.log("Success:", values);
    const res = await http.post("/login", values);
    console.log("登录", res);
    const { code, message, token } = res.data;
    if (code == 1) {
      localStorage.setItem("token", token);
      localStorage.setItem("username", values.username);
      alert(message);
      if (values.remember) {
        localStorage.setItem("name", values.username);
        localStorage.setItem("psw", values.password);
      } else {
        localStorage.removeItem("name");
        localStorage.removeItem("psw");
      }
      const response = await http.get("/getUserInfo", { params: values });
      console.log(response);
      const { pic, name } = response.data.data;
      if (response.data.code == 1) {
        dispatch(
          setListSlice({
            pic: pic,
            Nickname: name,
          })
        );
      }
      window.location.href = "/home/index";
    }
  }, 800);
  const [form] = useForm();
  useEffect(() => {
    form.setFieldsValue({
      username: localStorage.getItem("name"),
      password: localStorage.getItem("psw"),
    });
  }, []);
  return (
    <div>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[
            { required: true, message: "Please input your username!" },
            { pattern: /^.{4,8}$/, message: "四到八位" },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[
            { required: true, message: "Please input your password!" },
            {
              pattern: /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[_]).{4,8}$/,
              message: "数字字母下划线",
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          label="验证码"
          //   layout="inline"

          rules={[
            { required: true, message: "Please input your password!" },
            {
              pattern: /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{4}$/,
              message: "数字字母",
            },
          ]}
        >
          <Form.Item name="code">
            <Input style={{ width: 200 }} />
          </Form.Item>
          <Button
            disabled={isRun}
            onClick={() => {
              start();
              const code = Math.random().toString(36).slice(2, 6);
              setInterval(() => {
                form.setFieldsValue({
                  code: code,
                });
              }, 3000);
            }}
          >
            {isRun ? count + "后重新获取" : "获取验证码"}
          </Button>
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked" label={null}>
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item label={null}>
          <Button
            type="primary"
            htmlType="submit"
            disabled={
              !form.isFieldsTouched(["username", "password", "code"], true) ||
              !!form.getFieldsError().filter(({ errors }) => errors.length)
                .length
            }
          >
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
